package main

import (
	"context"
	"encoding/json"
	"feishup2pclient/api"
	"feishup2pclient/msg"
	"feishup2pclient/socket"
	"io/ioutil"
	"os/exec"
	run "runtime"
	"time"

	//"feishup2pclient/data"
	MSG "feishup2pclient/msg"
	"fmt"
	"os"
	"sync/atomic"

	//"feishup2pclient/p2p"

	"github.com/wailsapp/wails/v2/pkg/runtime"
	"golang.org/x/sys/windows/registry"
)

var MsgChan1 = make(chan string) //通道
var MsgChan2 = make(chan string) //通道
var MsgChan3 = make(chan string) //通道
type Todos struct {
	ctx       context.Context
	filname   string
	flag      int32
	fireState uint64
}

func NewTodos() *Todos {
	return &Todos{}
}

func (c *Todos) Config(str string) {
	println("configtest!")
	runtime.EventsEmit(Ctxa, "config", str)
}

func (c *Todos) test(str string) {
	msg.SendMessage(str)
}

func (a *Todos) startup(ctx context.Context) {
	a.ctx = ctx
	a.filname = "aaaaaaaaaaaa"
	//go a.Chana()
}

// 日志信息
func (t *Todos) SendMsg(str string) {
	// fmt.Printf("SendMsg %s filname %s\n", str, t.filname)
	runtime.EventsEmit(Ctxa, "message", str)
}

// nat信息
func (t *Todos) SendNat(str string) {
	// fmt.Printf("SendMsg %s filname %s\n", str, t.filname)
	runtime.EventsEmit(Ctxa, "nat", str)
}

// 超时信息
func (t *Todos) Sendtimeout(str string) {
	// fmt.Printf("Sendtimeout %s filname %s\n", str, t.filname)
	runtime.EventsEmit(Ctxa, "timeout", str)
}

// 操作成功信息
func (t *Todos) SendSuccess(str string) {
	// fmt.Printf("Sendtimeout %s filname %s\n", str, t.filname)
	runtime.EventsEmit(Ctxa, "success", str)
}

// 操作失败信息
func (t *Todos) SendErr(str string) {
	// fmt.Printf("Sendtimeout %s filname %s\n", str, t.filname)
	runtime.EventsEmit(Ctxa, "err", str)
}
func (t *Todos) Chana() {

	if !atomic.CompareAndSwapInt32(&t.flag, 0, 1) {
		return
	}

	for {
		defer func() {
			atomic.StoreInt32(&t.flag, 0)
		}()

		select {
		case msg := <-MSG.MsgChan:
			t.SendMsg(msg)

		case msg := <-MSG.MsgtimeoutChan:
			t.Sendtimeout(msg)
		case msg := <-MSG.NatCheckChan:
			fmt.Printf("nat检测\n")
			t.SendNat(msg)

		case msg := <-MSG.SuccessChan:
			t.SendSuccess(msg)

		case msg := <-MSG.ErrChan:
			t.SendErr(msg)

		case msg := <-MSG.ConfigChan:
			t.Config(msg)
		case <-time.After(1000 * time.Millisecond):

		}
	}

}

// 启动服务

func (t *Todos) Run() string {
	//token = data.Token{}
	msg.ErrCheck(fmt.Sprintf("token : %s", &token))
	msg.ErrCheck(fmt.Sprintf("SrcJson : %s", SrcJson))
	err := json.Unmarshal([]byte(SrcJson), &token)
	if err != nil {
		// fmt.Printf("token格式错误:%v\n", err)
		MSG.SendMessage(fmt.Sprintf("token格式错误:%v\n", err))

		return fmt.Sprintf("token格式错误:%v\n", err)
	}
	if len(token.Server) == 0 {
		// fmt.Printf("服务端地址为空:%v\n", err)
		MSG.SendMessage(fmt.Sprintf("服务端地址为空:%v\n", err))
		return fmt.Sprintf("服务端地址为空:%v\n", err)
	}
	if len(token.CIp) == 0 {
		MSG.SendMessage(fmt.Sprintf("客户端IP为空:%v\n", err))
		// fmt.Printf("客户端IP为空:%v\n", err)
		return fmt.Sprintf("客户端IP为空:%v\n", err)
	}
	if len(token.Cn) == 0 {
		MSG.SendMessage(fmt.Sprintf("客户端网卡名称为空:%v\n", err))
		// fmt.Printf("客户端网卡名称为空:%v\n", err)
		return fmt.Sprintf("客户端网卡名称为空:%v\n", err)
	}
	if len(*runBird) == 0 {
		*runBird = os.Getenv("ospf")
	}

	ctx, stopFunc = context.WithCancel(context.Background())
	// log.Infof("ospf:" + *runBird)
	//p2p.StartP2P(token.Cn, token.CIp)
	go api.InitApi()
	go t.Chana()
	socket.StartSocket(ctx, token)

	return "ok"
}

// 防火墙状态查询
func (c *Todos) FireCheck() {
	k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile`, registry.ALL_ACCESS)
	if err != nil {
		// log.Fatal(err)
	}
	defer k.Close()

	// // 获取当前防火墙状态
	value, _, err := k.GetIntegerValue("EnableFirewall")
	// println(fmt.Sprintf("权限状态为: %v", value))
	if err != nil {
		// log.Fatal(err)
		return
	}
	msg.SendMessage(fmt.Sprintf("防火墙状态: %s\n", string(value)))
	// fmt.Printf("防火墙状态: %v\n", value)
	c.fireState = value
}

// 防火墙查看
func (c *Todos) GetFireState() string {
	c.FireCheck()
	if c.fireState == 0 {
		return "close"
	}
	return "open"
}

// 防火墙开启
func (c *Todos) OpenFireWall() string {
	c.FireCheck()
	if c.fireState == 1 {
		return "fail"
	}
	enableCmd := exec.Command("netsh", "advfirewall", "set", "allprofiles", "state", "on")
	err := enableCmd.Run()
	if err != nil {
		// log.Fatal(err)
	}
	c.FireCheck()
	if c.fireState == 1 {
		return "sussess"
	}
	return "fail"
}

// 防火墙关闭
func (c *Todos) CloseFireWall() string {
	c.FireCheck()
	if c.fireState == 0 {
		msg.SuccessCheck("防火墙已关闭")
		return "fail"
	}
	disableCmd := exec.Command("netsh", "advfirewall", "set", "allprofiles", "state", "off")
	disableCmd.Run()
	msg.SuccessCheck("防火墙已开启")
	c.FireCheck()
	if c.fireState == 0 {
		return "sussess"
	}
	return "fail"
}

func (c *Todos) SetSuccessLogs(str string) {
	msg.SuccessCheck(fmt.Sprintf("timeout msg:%s", str))
}
func (c *Todos) SetErrLogs(str string) {
	msg.ErrCheck(fmt.Sprintf("timeout msg:%s", str))
}
func (c *Todos) GetAppMsg() map[string]interface{} {
	data, err := ioutil.ReadFile("app.json") // file.json为要读取的JSON文件名
	if err != nil {
		msg.PanicCheck("应用信息文件不存在")
		panic(err)
	}

	var result map[string]interface{}
	err = json.Unmarshal(data, &result)
	if err != nil {
		panic(err)
	}
	result[`System version`] = run.GOOS
	return result
}
